"""
中间件（拦截过滤器）----> 装饰器 ----> 处理横切关注功能
"""
from urllib.parse import quote

from django.http import JsonResponse
from django.shortcuts import redirect


LOGIN_REQUIRED_URLS = {
    '/report/',
    '/praise/',
    '/criticize/',
    '/export/',
    '/bar/',
}


def check_login_middleware(view_func):

    def wrapper(request, *args, **kwargs):
        if request.path in LOGIN_REQUIRED_URLS:
            if request.session.get('userid') is None:
                if request.path in ('/praise/', '/criticize/'):
                    return JsonResponse({'code': 10002, 'message': '请先登录'})
                else:
                    return redirect(f'/login/?hint={quote("请先登录")}')
        return view_func(request, *args, **kwargs)

    return wrapper
